import axios from 'axios';
import {baseUrl} from '@/config/env';
import {getUserInfo, messageHandle} from '@/utils';
import {msgCode} from "@/config/string";
import {clearStorage} from "@/config/sessions";
import EventBus from "@/modules/eventBus";
import store from "../store";

const Ax = axios.create({
  baseURL: `${baseUrl}`,
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});

// 请求拦截器
Ax.interceptors.request.use(
  config => {
    const headers = config.headers;
    const userInfo = getUserInfo();
    config.headers = {
      ...headers,
      token: userInfo.token,
      userId: userInfo.userId,
    };
    config.cancelToken = new axios.CancelToken((cancel) => {
      //使用vuex 定义pushCancel，请求进来存入
      store.dispatch('pushCancel', {cancelToken: cancel})
    });
    if (config.url.includes('/file/upload')) {
      config.timeout = 300000;
    }
    return config;
  },
  error => {
    console.log('##### request error #####', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
Ax.interceptors.response.use(
  (response = {}) => {
    const resp = response.data || {};
    const {code, msg = ''} = resp;
    if (code !== 0) {
      const message = msg || '服务器异常，请稍后重试';
      switch (code) {
        case msgCode.TOKEN_EXPIRE:
        case msgCode.USER_INVALIDATE:
          store.dispatch('clearCancel');
          messageHandle({type: 'warning', msg: message});
          EventBus.$emit('tokenExpired', true);
          clearStorage();
          return Promise.reject(new Error(message));
        case msgCode.DATA_DUPLICATE:
        case msgCode.DATA_PROTECT:
          messageHandle({type: 'warning', msg: message});
          return Promise.reject(new Error(message));
        case msgCode.SYSTEM_ERROR:
        default:
          messageHandle({type: 'error', msg: message});
          return Promise.reject(new Error(message));
      }
    } else {
      return resp;
    }
  },
  (error = {}) => {
    if (axios.isCancel(error)) {
      // 使用isCancel 判断是否是主动取消请求
      return new Promise(() => {
      });
    } else {
      console.log('##### response error #####', error);
      const message = '网络错误，请稍后重试！';
      messageHandle({type: 'error', msg: message});
      return Promise.reject(new Error(message));
    }

  }
);

export default Ax;
